package org.simple.uiapi.api

import groovy.transform.CompileStatic
import org.nutz.dao.pager.Pager
import org.nutz.http.Header
import org.nutz.ioc.loader.annotation.IocBean
import org.nutz.mvc.annotation.At
import org.nutz.mvc.annotation.Ok
import org.simple.base.json.util.JsonUtil
import org.simple.base.model.GridModel
import org.simple.base.model.QuickMap
import org.simple.base.nutz.action.CommonAction
import org.simple.base.util.JsonApiUtil
import org.simple.cfg.api.SysCfg
import org.simple.query.util.QueryUtil

@At("/api/ui/")
@IocBean
class BootstrapApi extends CommonAction {
    @At
    @Ok("json")
    GridModel grid() {
        Integer start = request.getParameter("start")?.toInteger() ?: 0
        Integer limit = request.getParameter("limit")?.toInteger() ?: Pager.DEFAULT_PAGE_SIZE

        int pageNumber = start / limit + 1

        if (pageNumber * limit < start) {
            pageNumber++
        }

        QuickMap filters = new QuickMap(new QueryUtil().initRequest(request).params())
        // 加入grid的排序方式
        filters.sortBy = request.getParameter("sortBy")
        filters.sortDir = request.getParameter("sortDir")

        def req = [
                pager  : new Pager(
                        pageNumber: pageNumber,
                        pageSize: limit
                ),
                filters: filters,
                param  : getJsonParam(),
        ]


        QuickMap response = call(req)

        if (!response || response.returnCode != '0') {
            return null
        }

        return new GridModel(
                total: response?.body?.pager?.recordCount ?: 0,
                rows: response?.body?.rows as List ?: []
        )
    }

    private QuickMap getJsonParam() {
        String json = request.getParameter("param")

        if (json) {
            return JsonUtil.fromJson(QuickMap, json)
        }

        return null
    }

    private QuickMap call(Map map) {
        int port = request.localPort

        if (request.scheme == 'https') {
            port = SysCfg.get().getInt("port")
        }

        String api = "http://${request.localAddr}:${port}${request.contextPath}" + request.getParameter("api")
        return JsonApiUtil.call(api, [(JsonApiUtil.POST_DATA): map, (JsonApiUtil.HEADER): Header.create(
                [Cookie        : "JSESSIONID=" + request.session.id,
                 'Content-Type': 'application/json']
        )], QuickMap)
    }
}
